package cn.wolfcode.resolver;

import cn.wolfcode.annotation.UserParam;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.redis.IUserInfoRedisService;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 用户参数解析器:将请求映射方法形式参数声明的UserInfo类型的参数解析成当前登入用户对象并注入
 * @Author: 伍家钰
 * @Date: 2020/8/15 20:12
 * @Version: 1.0
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Resource
    private IUserInfoRedisService userInfoRedisService;

    // 指定当前解析器解析的参数类型
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        // 表示当参数类型为UserInfo同时贴了UserParam注解的参数才进行解析
        return methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * 当上面的方法返回true时执行解析逻辑,获取当前登入用户信息,注入给UserInfo类型的参数
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 获取request对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        // 获取token
        String token = request.getHeader("token");
        // 从redis中获取当前登入用户对象
        UserInfo userInfo = userInfoRedisService.getByToken(token);
        return userInfo;
    }
}
